package comm;

/**
 * @author Dujie
 * @create 2025/8/4
 * @since 1.0.0
 */
import com.fazecast.jSerialComm.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.atomic.AtomicBoolean;

public class SerialFullDuplex {
    public static void main(String[] args) {
        final AtomicBoolean run = new AtomicBoolean(true);
        // 获取可用串口
        SerialPort[] ports = SerialPort.getCommPorts();
        for (SerialPort port : ports) {
            System.out.println(port.getSystemPortName());
        }

        SerialPort serialPort = SerialPort.getCommPort("COM2"); // 修改为你的串口

        serialPort.openPort();
        serialPort.setBaudRate(9600);

        // 读线程
        Thread readThread = new Thread(() -> {
            byte[] buffer = new byte[1024];
            while (run.get()) {
                int numRead = serialPort.readBytes(buffer, buffer.length);
                if (numRead > 0) {
                    String received = new String(buffer, 0, numRead);
                    System.out.println("收到: " + received);
                }
            }
        });

        // 写线程
        Thread writeThread = new Thread(() -> {
            try (BufferedReader console = new BufferedReader(new InputStreamReader(System.in))) {
                while (run.get()) {
                    String message = console.readLine();
                    if (message.equals("exit")) {
                        run.set(false);
                    };
                    serialPort.writeBytes(message.getBytes(), message.length());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        readThread.start();
        writeThread.start();
    }
}